package 剑指offer;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * Created by yang on 2016/8/24.
 */
public class OrderArrayWithOddFirstEvenLast {
    public void reOrderArray(int [] array) {

        ArrayList<Integer> listOdd = new ArrayList<Integer>();
        ArrayList<Integer> listEven = new ArrayList<Integer>();
        int len = array.length;
        for(int i = 0; i < len; i++) {
            if(array[i] % 2 == 0) {
                listEven.add(array[i]);
            }else{
                listOdd.add(array[i]);
            }
        }
        listOdd.addAll(listEven);

        for(int i = 0; i < len; i++) {
            array[i] = listOdd.get(i);
        }
    }

    public void ReOrderArray(int [] array) {

        ArrayList<Integer> res = new ArrayList<>();
        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletionService<ArrayList<Integer>> completionServiceOdd = new ExecutorCompletionService<ArrayList<Integer>>(executorService);
        completionServiceOdd.submit(new OddTask(array));

        CompletionService<ArrayList<Integer>> completionServiceEven = new ExecutorCompletionService<ArrayList<Integer>>(executorService);
        completionServiceEven.submit(new EvenTask(array));

        try {
            Future<ArrayList<Integer>> futureOdd = completionServiceOdd.take();
            Future<ArrayList<Integer>> futureEven = completionServiceEven.take();

            res = futureOdd.get();
            res.addAll(futureEven.get());
        } catch (Exception e) {
            e.printStackTrace();
        }

        int len = res.size();
        for(int i = 0;i < len; i++ ) {
            array[i] = res.get(i);
        }
    }

    class EvenTask implements Callable {

        ArrayList<Integer> listEven = new ArrayList<>();
        private int []arr;
        public EvenTask(int []arr) {
            this.arr = arr;
        }

        @Override
        public ArrayList<Integer> call() throws Exception {
            for(int i:arr) {
                if(i % 2 == 0) {
                    listEven.add(i);
                }
            }
            return listEven;
        }
    }
    class OddTask implements Callable {

        private ArrayList<Integer> listOdd = new ArrayList<>();
        private int []arr;
        public OddTask(int []arr) {
            this.arr = arr;
        }
        @Override
        public ArrayList<Integer> call() throws Exception {
            for(int i:arr) {
                if (i % 2 != 0) {
                    listOdd.add(i);
                }
            }
            return listOdd;
        }
    }
}
